#include "bridge_motors.h"
#include "driver/ledc.h"


#define LEDC_TIMER              LEDC_TIMER_0
#define LEDC_MODE               LEDC_LOW_SPEED_MODE
#define LEDC_DUTY_RES           LEDC_TIMER_13_BIT // Set duty resolution to 13 bits
#define LEDC_DUTY               (2<<13) // Set duty to 50%. (2 ** 13) * 50% = 4096

int device_pwm_init(int pwm_hz,int pwm_channel,int pwm_io)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode       = LEDC_MODE,
        .duty_resolution  = LEDC_DUTY_RES,
        .timer_num        = LEDC_TIMER,
        .freq_hz          = pwm_hz,  // Set output frequency at 4 kHz
        .clk_cfg          = LEDC_AUTO_CLK
    };
    ledc_timer_config(&ledc_timer);

    // Prepare and then apply the LEDC PWM channel configuration
    ledc_channel_config_t ledc_channel = {
        .speed_mode     = LEDC_MODE,
        .channel        = pwm_channel,
        .timer_sel      = LEDC_TIMER,
        .intr_type      = LEDC_INTR_DISABLE,
        .gpio_num       = pwm_io,
        .duty           = 0, // Set duty to 0%
        .hpoint         = 0
    };
    ledc_channel_config(&ledc_channel);
    return 0;
}

int device_pwm_set(int pwm_channel,int pwm_duty)
{
    ledc_set_duty(LEDC_MODE, pwm_channel, pwm_duty);
    ledc_update_duty(LEDC_MODE, pwm_channel);
    printf("set pwm %d duty %d\n", pwm_channel, pwm_duty);

    return 0;
}

int device_pwm_deinit()
{
    return 0;
}